<script setup>
import { ref } from "vue";
import {userStore} from "@/stores/userStore.js";
import axios from "axios";
import {host_custom} from "@/host.js";
import {storeToRefs} from "pinia";

const userAction = storeToRefs(userStore())
const themeToggleBtn = ref()

const isDarkMode = ref(!!userAction.userSetting.value.theme)
const toggleTheme = () =>{
  updateTheme()
  isDarkMode.value = !isDarkMode.value
  themeToggleBtn.value.classList.toggle('active')
  if (isDarkMode.value) {
    document.documentElement.setAttribute('data-bs-theme', 'dark')
  } else{
    document.documentElement.setAttribute('data-bs-theme', 'light')
  }
}

const updateTheme = async () => {
  const rs = await axios.put(host_custom+'/updateUserTheme', { uid: userAction.userInfo.value.id })
  if (rs.status === 200) {
    userAction.userSetting.value.theme ? userAction.userSetting.value.theme = 0 : userAction.userSetting.value.theme = 1
    return void 0
  } else {
    console.error(rs.data)
  }
}

</script>

<template>
  <div class="themeToggleBtn" :class="{active: isDarkMode}" ref="themeToggleBtn" @click.prevent="toggleTheme">
    <span>Dark</span>
    <span>Light</span>
    <div class="themeIcon"><font-awesome-icon :icon="['fas', isDarkMode?'moon':'sun']" :style="{'color': isDarkMode? '#165fbd': '#f3d16e'}"/></div>
  </div>
</template>

<style scoped>
.themeToggleBtn span {
  user-select: none;
  transition: all 200ms ease-in-out;
  position: absolute;
  font-weight: 600;
  font-size: 12px;
}
.themeToggleBtn span:nth-of-type(2){
  top: 3px;
  color: #f3d16e;
  right: 5px;
}
.themeToggleBtn span:nth-of-type(1){
  top: 20px;
  color: #165fbd;
  left: 5px;
}
.themeToggleBtn {
  padding: 2px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: flex;
  align-items: center;
  width: 50px;
  height: 20px;
  border-radius: 20px;
  border: 1px solid #f3d16e;
  box-sizing: content-box;
}
.themeIcon {
  display: flex;
  justify-content: center;
  align-items: center;
  left: 0;
  transition: all 200ms ease-in-out;
  position: relative;
  /* //background-color: #38bd38; */
  height: 20px;
  width: 20px;
  border-radius: 50%;
}
.themeToggleBtn.active .themeIcon {
  left: 30px;
}

.themeToggleBtn.active {
  border: 1px solid #165fbd;
}

.themeToggleBtn.active span:nth-of-type(2) {
  top: -20px;
}

.themeToggleBtn.active span:nth-of-type(1) {
  top: 3px;
}
</style>